package activity;

import java.io.File;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import com.easemob.EMError;
import com.easemob.EMEventListener;
import com.easemob.EMNotifierEvent;
import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMConversation;
import com.easemob.chat.EMMessage;
import com.easemob.chat.ImageMessageBody;
import com.easemob.chat.TextMessageBody;
import com.easemob.chat.VoiceMessageBody;
import com.easemob.util.EasyUtils;
import com.easemob.util.PathUtil;
import com.easemob.util.VoiceRecorder;
import com.qzhy.female.R;

import Constant.Constance;
import adapter.ExpressionAdapter;
import adapter.ExpressionPagerAdapter;
import adapter.MessageAdapter;
import adapter.VoicePlayClickListener;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.PowerManager;
import android.provider.MediaStore;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.ClipboardManager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import app.BaseApp;
import app.HXSDKHelper;
import utils.CommonUtils;
import utils.ImageUtils;
import utils.SmileUtils;
import utils.ToastUtils;
import widget.ExpandGridView;
import widget.PasteEditText;

public class ChatActivity extends BaseActivity implements View.OnClickListener, EMEventListener, View.OnFocusChangeListener, TextWatcher, SwipeRefreshLayout.OnRefreshListener {
    /**
     * 状态
     */
    private static final String TAG = "ChatActivity";
    private static final int REQUEST_CODE_EMPTY_HISTORY = 2;
    public static final int REQUEST_CODE_CONTEXT_MENU = 3;
    private static final int REQUEST_CODE_MAP = 4;
    public static final int REQUEST_CODE_TEXT = 5;
    public static final int REQUEST_CODE_VOICE = 6;
    public static final int REQUEST_CODE_PICTURE = 7;
    public static final int REQUEST_CODE_LOCATION = 8;
    public static final int REQUEST_CODE_NET_DISK = 9;
    public static final int REQUEST_CODE_FILE = 10;
    public static final int REQUEST_CODE_COPY_AND_PASTE = 11;
    public static final int REQUEST_CODE_PICK_VIDEO = 12;
    public static final int REQUEST_CODE_DOWNLOAD_VIDEO = 13;
    public static final int REQUEST_CODE_VIDEO = 14;
    public static final int REQUEST_CODE_DOWNLOAD_VOICE = 15;
    public static final int REQUEST_CODE_SELECT_USER_CARD = 16;
    public static final int REQUEST_CODE_SEND_USER_CARD = 17;
    public static final int REQUEST_CODE_CAMERA = 18;
    public static final int REQUEST_CODE_LOCAL = 19;
    public static final int REQUEST_CODE_CLICK_DESTORY_IMG = 20;
    public static final int REQUEST_CODE_GROUP_DETAIL = 21;
    public static final int REQUEST_CODE_SELECT_VIDEO = 23;
    public static final int REQUEST_CODE_SELECT_FILE = 24;
    public static final int REQUEST_CODE_ADD_TO_BLACKLIST = 25;

    public static final int RESULT_CODE_COPY = 1;
    public static final int RESULT_CODE_DELETE = 2;
    public static final int RESULT_CODE_FORWARD = 3;
    public static final int RESULT_CODE_OPEN = 4;
    public static final int RESULT_CODE_DWONLOAD = 5;
    public static final int RESULT_CODE_TO_CLOUD = 6;
    public static final int RESULT_CODE_EXIT_GROUP = 7;

    public static final int CHATTYPE_SINGLE = 1;
    public static final int CHATTYPE_GROUP = 2;
    public static final int CHATTYPE_CHATROOM = 3;

    public static final String COPY_IMAGE = "EASEMOBIMG";
    public static int resendPos;


    private int chatType;//聊天模式
    private String toChatUsername;//聊天对象
    private int toChatPic;//聊天对象的头像

    /**
     * 控件
     */
    private ImageView iv_emoticons_normal;
    private ImageView iv_emoticons_checked;
    private LinearLayout btnContainer;
    private Button btnMore;
    private ImageButton ibBack;
    private ImageView ivClear;
    private ListView listView;
    private Button buttonSetModeVoice;
    private Button buttonSetModeKeyboard;
    private RelativeLayout buttonPressToSpeak;
    private RelativeLayout rlInput;
    private RelativeLayout recordingContainer;
    private LinearLayout more;
    private LinearLayout emojiIconContainer;
    private ViewPager expressionViewpager;
    private ImageView micImage;
    private TextView recordingHint;
    private View etBg;
    private PasteEditText etInput;
    private Button btSend;
    private TextView tvToChat;
//    private ContactBean bean;
    private ImageView btnTakePic;
    private ImageView btnPicture;
    private SwipeRefreshLayout swipeRefreshLayout;
    private ImageView ivClearHistory;

    /**
     * 显示表情面板，按钮面板等的状态
     */
    private static final int KEY_BOARD_STYLE_TXT = 0;//文字输入
    private static final int KEY_BOARD_STYLE_VOICE = 1;//语音输入
    private int key_board_flag = KEY_BOARD_STYLE_TXT;
    private static final int EMOTION_CHECKED_NON = 0;
    private static final int EMOTION_CHECEKD = 1;
    private int currentEmotionChecedState = EMOTION_CHECKED_NON;
    private static final int SHOW_BTN_CONTAINER = 0;
    private static final int SHOW_BTN_CONTAINER_NO = 1;
    private int currentBtnShowState = SHOW_BTN_CONTAINER;
 

    public boolean isRobot;
    private EMConversation conversation;
    private boolean isloading;
    private final int pagesize = 20;
    private boolean haveMoreData = true;
    private MessageAdapter adapter;
    private InputMethodManager manager;
    public String playMsgId;
    private PowerManager.WakeLock wakeLock;
    private Drawable[] micImages;
    private Handler micImageHandler = new Handler() {
        @Override
        public void handleMessage(android.os.Message msg) {
            // 切换msg切换图片
            micImage.setImageDrawable(micImages[msg.what]);
        }
    };
    private VoiceRecorder voiceRecorder;
    private SharedPreferences sp;
    private SharedPreferences.Editor et;
    private List<String> reslist;
    private File cameraFile;
    private ClipboardManager clipboard;
    public static ChatActivity activityInstance = null;
	private String userNickName;


    @Override

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chat);
        activityInstance = this;
        sp = getSharedPreferences(Constance.CHATS.SP_NAME, MODE_PRIVATE);
        et = sp.edit();
        initParams();
        initAnimList();
        initListener();
        initAction();
    }
	private void initParams() {
        wakeLock = ((PowerManager) getSystemService(Context.POWER_SERVICE)).newWakeLock(
                PowerManager.SCREEN_DIM_WAKE_LOCK, "demo");
        manager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        ibBack = (ImageButton) findViewById(R.id.ib_back);
        listView = (ListView) findViewById(R.id.lv);
        micImage = (ImageView) findViewById(R.id.mic_image);
        buttonSetModeVoice = (Button) findViewById(R.id.btn_set_mode_voice);
        buttonSetModeKeyboard = (Button) findViewById(R.id.btn_set_mode_keyboard);
        buttonPressToSpeak = (RelativeLayout) findViewById(R.id.btn_press_to_speak);
        recordingHint = (TextView) findViewById(R.id.recording_hint);
        recordingContainer = (RelativeLayout) findViewById(R.id.recording_container);
        etInput = (PasteEditText) findViewById(R.id.et_input);
        rlInput = (RelativeLayout) findViewById(R.id.rl_et_input_container);
        btSend = (Button) findViewById(R.id.btn_send);
        tvToChat = (TextView) findViewById(R.id.tv_tochat);
        etBg = (View) findViewById(R.id.et_bg);
        iv_emoticons_normal = (ImageView) findViewById(R.id.iv_emoticons_normal);
        iv_emoticons_checked = (ImageView) findViewById(R.id.iv_emoticons_checked);
        more = (LinearLayout) findViewById(R.id.more);
        emojiIconContainer = (LinearLayout) findViewById(R.id.ll_face_container);
        expressionViewpager = (ViewPager) findViewById(R.id.vPager);
        btnMore = (Button) findViewById(R.id.btn_sel_pic);
        btnContainer = (LinearLayout) findViewById(R.id.ll_btn_container);
        btnTakePic = (ImageView) findViewById(R.id.btn_take_picture);
        btnPicture = (ImageView) findViewById(R.id.btn_picture);
        swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.chat_swipe_layout);
        ivClearHistory = (ImageView) findViewById(R.id.iv_clear_msg);
        clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
    }
    /**
     * 加载动画资源文件
     */
    private void initAnimList() {
        micImages = new Drawable[]{getResources().getDrawable(R.drawable.record_animate_01),
                getResources().getDrawable(R.drawable.record_animate_02),
                getResources().getDrawable(R.drawable.record_animate_03),
                getResources().getDrawable(R.drawable.record_animate_04),
                getResources().getDrawable(R.drawable.record_animate_05),
                getResources().getDrawable(R.drawable.record_animate_06),
                getResources().getDrawable(R.drawable.record_animate_07),
                getResources().getDrawable(R.drawable.record_animate_08),
                getResources().getDrawable(R.drawable.record_animate_09),
                getResources().getDrawable(R.drawable.record_animate_10),
                getResources().getDrawable(R.drawable.record_animate_11),
                getResources().getDrawable(R.drawable.record_animate_12),
                getResources().getDrawable(R.drawable.record_animate_13),
                getResources().getDrawable(R.drawable.record_animate_14),};
        voiceRecorder = new VoiceRecorder(micImageHandler);

        // 表情list
        reslist = getExpressionRes(35);
        // 初始化表情viewpager
        List<View> views = new ArrayList<View>();
        View gv1 = getGridChildView(1);
        View gv2 = getGridChildView(2);
        views.add(gv1);
        views.add(gv2);
        expressionViewpager.setAdapter(new ExpressionPagerAdapter(views));
    }

    private List<String> getExpressionRes(int getSum) {
        List<String> reslist = new ArrayList<String>();
        for (int x = 1; x <= getSum; x++) {
            String filename = "ee_" + x;

            reslist.add(filename);

        }
        return reslist;
    }

    /**
     * 获取表情
     *
     * @param i
     * @return
     */
    private View getGridChildView(int i) {
        View view = View.inflate(this, R.layout.expression_gridview, null);
        ExpandGridView gv = (ExpandGridView) view.findViewById(R.id.gridview);
        List<String> list = new ArrayList<String>();
        if (i == 1) {
            List<String> list1 = reslist.subList(0, 20);
            list.addAll(list1);
        } else if (i == 2) {
            list.addAll(reslist.subList(20, reslist.size()));
        }
        list.add("delete_expression");
        final ExpressionAdapter expressionAdapter = new ExpressionAdapter(this, 1, list);
        gv.setAdapter(expressionAdapter);
        gv.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String filename = expressionAdapter.getItem(position);
                try {
                    // 文字输入框可见时，才可输入表情
                    // 按住说话可见，不让输入表情
                    if (buttonSetModeKeyboard.getVisibility() != View.VISIBLE) {

                        if (filename != "delete_expression") { // 不是删除键，显示表情
                            // 这里用的反射，记得这里是自己项目里的simleutils的路径
                            Class clz = Class.forName("utils.SmileUtils");
                            Field field = clz.getField(filename);
                            etInput.append(SmileUtils.getSmiledText(ChatActivity.this,
                                    (String) field.get(null)));
                        } else { // 删除文字或者表情
                            if (!TextUtils.isEmpty(etInput.getText())) {

                                int selectionStart = etInput.getSelectionStart();// 获取光标的位置
                                if (selectionStart > 0) {
                                    String body = etInput.getText().toString();
                                    String tempStr = body.substring(0, selectionStart);
                                    int i = tempStr.lastIndexOf("[");// 获取最后一个表情的位置
                                    if (i != -1) {
                                        CharSequence cs = tempStr.substring(i, selectionStart);
                                        if (SmileUtils.containsKey(cs.toString()))
                                            etInput.getEditableText().delete(i, selectionStart);
                                        else
                                            etInput.getEditableText().delete(selectionStart - 1,
                                                    selectionStart);
                                    } else {
                                        etInput.getEditableText().delete(selectionStart - 1, selectionStart);
                                    }
                                }
                            }

                        }
                    }
                } catch (Exception e) {
                }

            }
        });
        return view;
    }

    private void initListener() {
        ibBack.setOnClickListener(this);
        buttonSetModeVoice.setOnClickListener(this);
        buttonSetModeKeyboard.setOnClickListener(this);
        btSend.setOnClickListener(this);
        etInput.setOnFocusChangeListener(this);
        iv_emoticons_normal.setOnClickListener(this);
        iv_emoticons_checked.setOnClickListener(this);
        etInput.setOnClickListener(this);
        etInput.addTextChangedListener(this);
        btnMore.setOnClickListener(this);
        btnTakePic.setOnClickListener(this);
        btnPicture.setOnClickListener(this);
        swipeRefreshLayout.setOnRefreshListener(this);
        ivClearHistory.setOnClickListener(this);
        listView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                hideSoftInput();
                switchBtnPan(SHOW_BTN_CONTAINER_NO, true);
                more.setVisibility(View.GONE);
                iv_emoticons_normal.setVisibility(View.VISIBLE);
                iv_emoticons_checked.setVisibility(View.INVISIBLE);
                emojiIconContainer.setVisibility(View.GONE);
                currentEmotionChecedState = EMOTION_CHECKED_NON;
                switchEmotionPan(currentEmotionChecedState);
                return false;
            }
        });

    }

    private void initAction() {

        getParamsFmLastActivity();
        tvToChat.setText(userNickName);
        if (chatType != CHATTYPE_CHATROOM) {
            onConversationInit();
            onListViewCreation();

            // show forward message if the message is not null
            String forward_msg_id = getIntent().getStringExtra(Constance.CHATS.FORWARD_MSG_ID);
            if (forward_msg_id != null) {
                // 显示发送要转发的消息
                forwardMessage(forward_msg_id);
            }
        }


    }

    /**
     * 转发消息
     *
     * @param forward_msg_id
     */
    private void forwardMessage(String forward_msg_id) {
        final EMMessage forward_msg = EMChatManager.getInstance().getMessage(forward_msg_id);
        EMMessage.Type type = forward_msg.getType();
        switch (type) {
            case TXT:
                // 获取消息内容，发送消息
                String content = ((TextMessageBody) forward_msg.getBody()).getMessage();
                sendText(content);
                break;
            case IMAGE:
                // 发送图片
                String filePath = ((ImageMessageBody) forward_msg.getBody()).getLocalUrl();
                if (filePath != null) {
                    File file = new File(filePath);
                    if (!file.exists()) {
                        // 不存在大图发送缩略图
                        filePath = ImageUtils.getThumbnailImagePath(filePath);
                    }
                    sendPicture(filePath);
                }
                break;
            default:
                break;
        }

        if (forward_msg.getChatType() == EMMessage.ChatType.ChatRoom) {
            EMChatManager.getInstance().leaveChatRoom(forward_msg.getTo());
        }
    }


    /**
     * 获取上个界面传送过来的值
     */
    private void getParamsFmLastActivity() {
        chatType = getIntent().getExtras().getInt(Constance.CHATS.CHATTYPE);
        toChatUsername = getIntent().getExtras().getString(Constance.CHATS.USERID);
        userNickName = getIntent().getExtras().getString(Constance.INTENT.USER_NAME);
        toChatPic = sp.getInt(toChatUsername, 0);
    }

    private void onConversationInit() {
        if (chatType == CHATTYPE_SINGLE) {
            conversation = EMChatManager.getInstance().getConversationByType(toChatUsername, EMConversation.EMConversationType.Chat);
        } else if (chatType == CHATTYPE_GROUP) {
            conversation = EMChatManager.getInstance().getConversationByType(toChatUsername, EMConversation.EMConversationType.GroupChat);
        } else if (chatType == CHATTYPE_CHATROOM) {
            conversation = EMChatManager.getInstance().getConversationByType(toChatUsername, EMConversation.EMConversationType.ChatRoom);
        }
        // 把此会话的未读数置为0
        conversation.markAllMessagesAsRead();
        // 初始化db时，每个conversation加载数目是getChatOptions().getNumberOfMessagesLoaded
        // 这个数目如果比用户期望进入会话界面时显示的个数不一样，就多加载一些
        final List<EMMessage> msgs = conversation.getAllMessages();
        int msgCount = msgs != null ? msgs.size() : 0;
        if (msgCount < conversation.getAllMsgCount() && msgCount < pagesize) {
            String msgId = null;
            if (msgs != null && msgs.size() > 0) {
                msgId = msgs.get(0).getMsgId();
            }
            if (chatType == CHATTYPE_SINGLE) {
                conversation.loadMoreMsgFromDB(msgId, pagesize);
            } else {
                conversation.loadMoreGroupMsgFromDB(msgId, pagesize);
            }
        }
    }

    private void onListViewCreation() {
        adapter = new MessageAdapter(this, toChatUsername, toChatPic);
        // 显示消息
        listView.setAdapter(adapter);
        adapter.refreshSelectLast();
        buttonPressToSpeak.setOnTouchListener(new PressToSpeakListener());

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {

            case R.id.ib_back:
                goback();
                break;
            case R.id.btn_send:
                String content = etInput.getText().toString().trim();
                if (TextUtils.isEmpty(content)) {
                    return;
                }
                sendText(content);
                break;
            case R.id.btn_set_mode_keyboard:
                key_board_flag = KEY_BOARD_STYLE_TXT;
                switchKeybordStyle(key_board_flag);
                break;
            case R.id.btn_set_mode_voice:
                key_board_flag = KEY_BOARD_STYLE_VOICE;
                switchKeybordStyle(key_board_flag);
                break;
            case R.id.iv_emoticons_normal:
                currentEmotionChecedState = EMOTION_CHECEKD;
                switchEmotionPan(currentEmotionChecedState);
                break;
            case R.id.iv_emoticons_checked:
                currentEmotionChecedState = EMOTION_CHECKED_NON;
                switchEmotionPan(currentEmotionChecedState);
                break;
            case R.id.et_input:
                switchBtnPan(SHOW_BTN_CONTAINER_NO, false);
                more.setVisibility(View.GONE);
                iv_emoticons_normal.setVisibility(View.VISIBLE);
                iv_emoticons_checked.setVisibility(View.INVISIBLE);
                emojiIconContainer.setVisibility(View.GONE);
                currentEmotionChecedState = EMOTION_CHECKED_NON;
                break;
            case R.id.btn_sel_pic:
                switchBtnPan(currentBtnShowState, true);
                break;
            case R.id.btn_take_picture:
                selectPicFromCamera();// 点击照相图标
                break;
            case R.id.btn_picture:
                selectPicFromLocal(); // 点击图片图标
                break;
            case R.id.iv_clear_msg:
                emptyHistory();
                break;
        }

    }

    /**
     * 点击清空聊天记录
     */
    public void emptyHistory() {
        String st5 = getResources().getString(R.string.Whether_to_empty_all_chats);
        startActivityForResult(new Intent(this, AlertDialog.class).putExtra("titleIsCancel", true).putExtra("msg", st5)
                .putExtra("cancel", true), REQUEST_CODE_EMPTY_HISTORY);
    }

    /**
     * 从图库获取图片
     */
    private void selectPicFromLocal() {
        Intent intent;
        if (Build.VERSION.SDK_INT < 19) {
            intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.setType("image/*");

        } else {
            intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        }
        startActivityForResult(intent, REQUEST_CODE_LOCAL);
    }

    /**
     * 拍照获取图片
     */
    private void selectPicFromCamera() {
        if (!CommonUtils.isExitsSdcard()) {
            String st = getResources().getString(R.string.sd_card_does_not_exist);
            ToastUtils.showToast(this, st);
            return;
        }

        cameraFile = new File(PathUtil.getInstance().getImagePath(), BaseApp.getUserName()
                + System.currentTimeMillis() + ".jpg");
        cameraFile.getParentFile().mkdirs();
        startActivityForResult(
                new Intent(MediaStore.ACTION_IMAGE_CAPTURE).putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(cameraFile)),
                REQUEST_CODE_CAMERA);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_CONTEXT_MENU) {
            switch (resultCode) {
                case RESULT_CODE_DELETE: // 删除消息
                    EMMessage deleteMsg = (EMMessage) adapter.getItem(data.getIntExtra("position", -1));
                    conversation.removeMessage(deleteMsg.getMsgId());
                    adapter.refreshSeekTo(data.getIntExtra("position", adapter.getCount()) - 1);
                    break;
                case RESULT_CODE_COPY: // 复制消息
                    EMMessage copyMsg = ((EMMessage) adapter.getItem(data.getIntExtra("position", -1)));
                    // clipboard.setText(SmileUtils.getSmiledText(ChatActivity.this,
                    // ((TextMessageBody) copyMsg.getBody()).getMessage()));
                    clipboard.setText(((TextMessageBody) copyMsg.getBody()).getMessage());
                    break;
                case RESULT_CODE_FORWARD: // 转发消息
//                    EMMessage forwardMsg = (EMMessage) adapter.getItem(data.getIntExtra("position", 0));
//                    Intent intent = new Intent(this, ContactListActivity.class);
//                    intent.putExtra(Constance.CHATS.FORWARD_MSG_ID, forwardMsg.getMsgId());
//                    startActivity(intent);

                    break;
            }
        }
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case REQUEST_CODE_CAMERA:
                    if (cameraFile != null && cameraFile.exists())
                        sendPicture(cameraFile.getAbsolutePath());//发送照片
                    break;
                case REQUEST_CODE_LOCAL:
                    if (data != null) {
                        Uri selectedImage = data.getData();
                        if (selectedImage != null) {
                            sendPicByUri(selectedImage);
                        }
                    }
                    break;
                case REQUEST_CODE_EMPTY_HISTORY:
                    // 清空会话
                    EMChatManager.getInstance().clearConversation(toChatUsername);
                    adapter.refresh();
                    break;
                case REQUEST_CODE_TEXT:
                case REQUEST_CODE_VOICE:
                case REQUEST_CODE_PICTURE:
                    resendMessage();
                    break;
                case REQUEST_CODE_COPY_AND_PASTE:
                    // 粘贴
                    if (!TextUtils.isEmpty(clipboard.getText())) {
                        String pasteText = clipboard.getText().toString();
                        if (pasteText.startsWith(COPY_IMAGE)) {
                            // 把图片前缀去掉，还原成正常的path
                            sendPicture(pasteText.replace(COPY_IMAGE, ""));
                        }

                    }
                    break;
            }
        }
    }

    /**
     * 重发消息
     */
    private void resendMessage() {
        EMMessage msg = null;
        msg = conversation.getMessage(resendPos);
        // msg.setBackSend(true);
        msg.status = EMMessage.Status.CREATE;

        adapter.refreshSeekTo(resendPos);

    }

    /**
     * 根据图库URI发送图片
     *
     * @param selectedImage
     */
    private void sendPicByUri(Uri selectedImage) {
        Cursor cursor = getContentResolver().query(selectedImage, null, null, null, null);
        String st8 = getResources().getString(R.string.cant_find_pictures);
        if (cursor != null) {
            cursor.moveToFirst();
            int columnIndex = cursor.getColumnIndex("_data");
            String picturePath = cursor.getString(columnIndex);
            cursor.close();
            cursor = null;

            if (picturePath == null || picturePath.equals("null")) {
                Toast toast = Toast.makeText(this, st8, Toast.LENGTH_SHORT);
                toast.setGravity(Gravity.CENTER, 0, 0);
                toast.show();
                return;
            }
            sendPicture(picturePath);
        } else {
            File file = new File(selectedImage.getPath());
            if (!file.exists()) {
                Toast toast = Toast.makeText(this, st8, Toast.LENGTH_SHORT);
                toast.setGravity(Gravity.CENTER, 0, 0);
                toast.show();
                return;

            }
            sendPicture(file.getAbsolutePath());
        }

    }

    /**
     * 发送图片
     *
     * @param filePath
     */
    private void sendPicture(final String filePath) {
        String to = toChatUsername;
        // create and add image message in view
        final EMMessage message = EMMessage.createSendMessage(EMMessage.Type.IMAGE);
        // 如果是群聊，设置chattype,默认是单聊
        if (chatType == CHATTYPE_GROUP) {
            message.setChatType(EMMessage.ChatType.GroupChat);
        } else if (chatType == CHATTYPE_CHATROOM) {
            message.setChatType(EMMessage.ChatType.ChatRoom);
        }

        message.setReceipt(to);
        ImageMessageBody body = new ImageMessageBody(new File(filePath));
        // 默认超过100k的图片会压缩后发给对方，可以设置成发送原图
        // body.setSendOriginalImage(true);
        message.addBody(body);
        if (isRobot) {
            message.setAttribute("em_robot_message", true);
        }
        conversation.addMessage(message);

        listView.setAdapter(adapter);
        adapter.refreshSelectLast();
        setResult(RESULT_OK);
    }

    /**
     * 显示按钮面板
     *
     * @param state
     */
    private void switchBtnPan(int state, boolean hideSoftinput) {
        if (hideSoftinput) {
            hideSoftInput();//关闭输入软盘
        }

        //---------关闭表情面板
        more.setVisibility(View.GONE);
        iv_emoticons_normal.setVisibility(View.VISIBLE);
        iv_emoticons_checked.setVisibility(View.INVISIBLE);
        emojiIconContainer.setVisibility(View.GONE);
        currentEmotionChecedState = EMOTION_CHECKED_NON;
        //-------
        switch (state) {
            case SHOW_BTN_CONTAINER:
                currentBtnShowState = SHOW_BTN_CONTAINER_NO;
                btnContainer.setVisibility(View.VISIBLE);
                break;
            case SHOW_BTN_CONTAINER_NO:
                currentBtnShowState = SHOW_BTN_CONTAINER;
                btnContainer.setVisibility(View.GONE);
                break;
        }

    }

    /**
     * 显示表情面板
     *
     * @param currentEmotionChecedState
     */
    private void switchEmotionPan(int currentEmotionChecedState) {
        switchBtnPan(SHOW_BTN_CONTAINER_NO, true);
        switch (currentEmotionChecedState) {
            case EMOTION_CHECEKD:
                etInput.requestFocus();//获取焦点，只有获取焦点后才能执行点击事件
                hideSoftInput();
                iv_emoticons_normal.setVisibility(View.INVISIBLE);
                iv_emoticons_checked.setVisibility(View.VISIBLE);
                etBg.setBackgroundColor(getResources().getColor(R.color.et_bg_focoused));
                more.setVisibility(View.VISIBLE);
                emojiIconContainer.setVisibility(View.VISIBLE);

                break;
            case EMOTION_CHECKED_NON:
                iv_emoticons_normal.setVisibility(View.VISIBLE);
                iv_emoticons_checked.setVisibility(View.INVISIBLE);
                more.setVisibility(View.GONE);
                emojiIconContainer.setVisibility(View.INVISIBLE);
                break;
        }
    }

    /**
     * 切换输入盘样式
     *
     * @param key_board_flag
     */
    private void switchKeybordStyle(int key_board_flag) {
        switchBtnPan(SHOW_BTN_CONTAINER_NO, true);//隐藏按钮面板
        switch (key_board_flag) {
            case KEY_BOARD_STYLE_TXT:
                buttonSetModeKeyboard.setVisibility(View.INVISIBLE);
                buttonPressToSpeak.setVisibility(View.INVISIBLE);
                buttonSetModeVoice.setVisibility(View.VISIBLE);
                rlInput.setVisibility(View.VISIBLE);
                break;
            case KEY_BOARD_STYLE_VOICE:
                currentEmotionChecedState = EMOTION_CHECKED_NON;
                switchEmotionPan(currentEmotionChecedState);
                buttonSetModeKeyboard.setVisibility(View.VISIBLE);
                buttonPressToSpeak.setVisibility(View.VISIBLE);
                buttonSetModeVoice.setVisibility(View.INVISIBLE);
                rlInput.setVisibility(View.INVISIBLE);
                hideSoftInput();
                break;
        }

    }

    /**
     * 关闭输入软盘
     */
    private void hideSoftInput() {
        if (getWindow().getAttributes().softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN) {
            if (getCurrentFocus() != null)
                manager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    public void sendText(String content) {
        if (content.length() > 0) {
            etInput.setText("");
            EMMessage message = EMMessage.createSendMessage(EMMessage.Type.TXT);
            // 如果是群聊，设置chattype,默认是单聊
            if (chatType == CHATTYPE_GROUP) {
                message.setChatType(EMMessage.ChatType.GroupChat);
            } else if (chatType == CHATTYPE_CHATROOM) {
                message.setChatType(EMMessage.ChatType.ChatRoom);
            }
            if (isRobot) {
                message.setAttribute("em_robot_message", true);
            }
            TextMessageBody txtBody = new TextMessageBody(content);
            // 设置消息body
            message.addBody(txtBody);
            // 设置要发给谁,用户username或者群聊groupid
            message.setReceipt(toChatUsername);
            // 把messgage加到conversation中
            conversation.addMessage(message);
            // 通知adapter有消息变动，adapter会根据加入的这条message显示消息和调用sdk的发送方法
            adapter.refreshSelectLast();
            setResult(RESULT_OK);

        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (adapter != null) {
            adapter.refresh();
        }

        //注册监听
        EMChatManager.getInstance().registerEventListener(
                this,
                new EMNotifierEvent.Event[]{EMNotifierEvent.Event.EventNewMessage, EMNotifierEvent.Event.EventOfflineMessage,
                        EMNotifierEvent.Event.EventDeliveryAck, EMNotifierEvent.Event.EventReadAck});
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        activityInstance = null;
        EMChatManager.getInstance().unregisterEventListener(this);//取消监听
    }


    @Override
    public void onBackPressed() {

        goback();
    }

    /**
     * 回退
     */
    private void goback() {
        if (more.getVisibility() == View.VISIBLE) {
            more.setVisibility(View.GONE);
            iv_emoticons_normal.setVisibility(View.VISIBLE);
            iv_emoticons_checked.setVisibility(View.INVISIBLE);
            hideSoftInput();
            currentEmotionChecedState = EMOTION_CHECKED_NON;
            return;
        }
        finish();
    }

    /**
     * 这里注意啦，启动模式是singletop，所以要重写intent的获取模式
     *
     * @param intent
     */
    @Override
    protected void onNewIntent(Intent intent) {

        // 点击notification bar进入聊天页面，保证只有一个聊天页面
        String username = intent.getStringExtra(Constance.CHATS.USERID);
        if (toChatUsername.equals(username))
            super.onNewIntent(intent);
        else {
            finish();
            startActivity(intent);
        }

    }

    public ListView getListView() {
        return listView;
    }

    @Override
    public void onEvent(EMNotifierEvent event) {
        switch (event.getEvent()) {
            case EventNewMessage: {
                //获取到message
                EMMessage message = (EMMessage) event.getData();

                String username = null;
                //群组消息
                if (message.getChatType() == EMMessage.ChatType.GroupChat || message.getChatType() == EMMessage.ChatType.ChatRoom) {
                    username = message.getTo();
                } else {
                    //单聊消息
                    username = message.getFrom();
                }

                //如果是当前会话的消息，刷新聊天页面
                if (username.equals(getToChatUsername())) {
                    refreshUIWithNewMessage();
                    if (!EasyUtils.isAppRunningForeground(this)) {//后台运行的时候才推送消息
                        HXSDKHelper.getInstance().getNotifier().onNewMsg(message);
                    }


                    // TODO: 2015/12/20 0020
                } else {
                    //如果消息不是和当前聊天ID的消息
                    HXSDKHelper.getInstance().getNotifier().onNewMsg(message);


                }

                break;
            }
            case EventDeliveryAck: {
                //获取到message
                EMMessage message = (EMMessage) event.getData();
                refreshUI();
                break;
            }
            case EventReadAck: {
                //获取到message
                EMMessage message = (EMMessage) event.getData();
                refreshUI();
                break;
            }
            case EventOfflineMessage: {
                //a list of offline messages
                //List<EMMessage> offlineMessages = (List<EMMessage>) event.getData();
                refreshUI();
                break;
            }
            default:
                break;
        }

    }

    private void refreshUI() {
        if (adapter == null) {
            return;
        }

        runOnUiThread(new Runnable() {
            public void run() {
                adapter.refresh();
            }
        });
    }

    /**
     * 刷新聊天界面
     */
    private void refreshUIWithNewMessage() {
        if (adapter == null) {
            return;
        }

        runOnUiThread(new Runnable() {
            public void run() {
                adapter.refreshSelectLast();
            }
        });
    }

    private String getToChatUsername() {

        return toChatUsername;
    }

    /**
     * 根据输入框的焦点状态改变背景
     *
     * @param v
     * @param hasFocus
     */
    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        if (hasFocus) {
            etBg.setBackgroundColor(getResources().getColor(R.color.et_bg_focoused));
        } else {
            etBg.setBackgroundColor(getResources().getColor(R.color.et_bg_not_focoused));
        }
    }

    /**
     * 监听输入框内容变化
     *
     * @param s
     * @param start
     * @param count
     * @param after
     */
    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        if (!TextUtils.isEmpty(s)) {
            btnMore.setVisibility(View.GONE);
            btSend.setVisibility(View.VISIBLE);
        } else {
            btnMore.setVisibility(View.VISIBLE);
            btSend.setVisibility(View.GONE);
        }
    }

    @Override
    public void afterTextChanged(Editable s) {

    }

    /**
     * 分页加载
     */
    @Override
    public void onRefresh() {
        new Handler().postDelayed(new Runnable() {

            @Override
            public void run() {
                if (listView.getFirstVisiblePosition() == 0 && !isloading && haveMoreData) {
                    List<EMMessage> messages;
                    try {
                        if (chatType == CHATTYPE_SINGLE) {
                            messages = conversation.loadMoreMsgFromDB(adapter.getItem(0).getMsgId(), pagesize);
                        } else {
                            messages = conversation.loadMoreGroupMsgFromDB(adapter.getItem(0).getMsgId(), pagesize);
                        }
                    } catch (Exception e1) {
                        swipeRefreshLayout.setRefreshing(false);
                        return;
                    }

                    if (messages.size() > 0) {
                        adapter.notifyDataSetChanged();
                        adapter.refreshSeekTo(messages.size() - 1);
                        if (messages.size() != pagesize) {
                            haveMoreData = false;
                        }
                    } else {
                        haveMoreData = false;
                    }

                    isloading = false;

                } else {
                    ToastUtils.showToast(ChatActivity.this, getResources().getString(R.string.no_more_messages));
                }
                swipeRefreshLayout.setRefreshing(false);
            }
        }, 1000);
    }

    /**
     * 按住说话listener
     */
    private class PressToSpeakListener implements View.OnTouchListener {

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    if (!CommonUtils.isExitsSdcard()) {
                        String st4 = getResources().getString(R.string.Send_voice_need_sdcard_support);
                        Toast.makeText(ChatActivity.this, st4, Toast.LENGTH_SHORT).show();
                        return false;
                    }
                    try {
                        v.setPressed(true);
                        wakeLock.acquire();
                        if (VoicePlayClickListener.isPlaying)
                            VoicePlayClickListener.currentPlayListener.stopPlayVoice();
                        recordingContainer.setVisibility(View.VISIBLE);
                        recordingHint.setText(getString(R.string.move_up_to_cancel));
                        recordingHint.setBackgroundColor(Color.TRANSPARENT);
                        voiceRecorder.startRecording(null, toChatUsername, getApplicationContext());
                    } catch (Exception e) {
                        e.printStackTrace();
                        v.setPressed(false);
                        if (wakeLock.isHeld())
                            wakeLock.release();
                        if (voiceRecorder != null)
                            voiceRecorder.discardRecording();
                        recordingContainer.setVisibility(View.INVISIBLE);
                        Toast.makeText(ChatActivity.this, R.string.recoding_fail, Toast.LENGTH_SHORT).show();
                        return false;
                    }

                    return true;
                case MotionEvent.ACTION_MOVE: {
                    if (event.getY() < 0) {
                        recordingHint.setText(getString(R.string.release_to_cancel));
                        recordingHint.setBackgroundResource(R.drawable.recording_text_hint_bg);
                    } else {
                        recordingHint.setText(getString(R.string.move_up_to_cancel));
                        recordingHint.setBackgroundColor(Color.TRANSPARENT);
                    }
                    return true;
                }
                case MotionEvent.ACTION_UP:
                    v.setPressed(false);
                    recordingContainer.setVisibility(View.INVISIBLE);
                    if (wakeLock.isHeld())
                        wakeLock.release();
                    if (event.getY() < 0) {
                        // discard the recorded audio.
                        voiceRecorder.discardRecording();

                    } else {
                        // stop recording and send voice file
                        String st1 = getResources().getString(R.string.Recording_without_permission);
                        String st2 = getResources().getString(R.string.The_recording_time_is_too_short);
                        String st3 = getResources().getString(R.string.send_failure_please);
                        try {
                            int length = voiceRecorder.stopRecoding();
                            if (length > 0) {
                                sendVoice(voiceRecorder.getVoiceFilePath(), voiceRecorder.getVoiceFileName(toChatUsername),
                                        Integer.toString(length), false);
                            } else if (length == EMError.INVALID_FILE) {
                                Toast.makeText(getApplicationContext(), st1, Toast.LENGTH_SHORT).show();
                            } else {
                                Toast.makeText(getApplicationContext(), st2, Toast.LENGTH_SHORT).show();
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            Toast.makeText(ChatActivity.this, st3, Toast.LENGTH_SHORT).show();
                        }

                    }
                    return true;
                default:
                    recordingContainer.setVisibility(View.INVISIBLE);
                    if (voiceRecorder != null)
                        voiceRecorder.discardRecording();
                    return false;
            }
        }
    }

    /**
     * 发送语音
     *
     * @param filePath
     * @param fileName
     * @param length
     * @param isResend
     */
    private void sendVoice(String filePath, String fileName, String length, boolean isResend) {
        if (!(new File(filePath).exists())) {
            return;
        }
        try {
            final EMMessage message = EMMessage.createSendMessage(EMMessage.Type.VOICE);
            // 如果是群聊，设置chattype,默认是单聊
            if (chatType == CHATTYPE_GROUP) {
                message.setChatType(EMMessage.ChatType.GroupChat);
            } else if (chatType == CHATTYPE_CHATROOM) {
                message.setChatType(EMMessage.ChatType.ChatRoom);
            }
            message.setReceipt(toChatUsername);
            int len = Integer.parseInt(length);
            VoiceMessageBody body = new VoiceMessageBody(new File(filePath), len);
            message.addBody(body);
            if (isRobot) {
                message.setAttribute("em_robot_message", true);
            }
            conversation.addMessage(message);
            adapter.refreshSelectLast();
            setResult(RESULT_OK);
            // send file
            // sendVoiceSub(filePath, fileName, message);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
